package com.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.proj.Info;
import com.proj.InfoInterface;
import com.proj.Tag;

import java.util.Collection;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static com.controller.Utility.errInternalError;

public class SpecialTagController {
    InfoInterface infoInterface;

    public String handle(String payload) {
        jInfoQuery p = JSON.parseObject(payload).getObject("value", jInfoQuery.class);
        Collection<Info> infos = infoInterface.getInfoByTagUnion(p.normal);

        for (JSONObject special : p.special) {
            String id = special.getString("id");
            switch (id) {
                case "others": {
                    Stream<Info> all_infos = infos.stream();
                    for (Object e : special.getJSONArray("value")) {
                        all_infos = all_infos.filter(
                                info -> info.getTags().stream()
                                        .map(Tag::getId)
                                        .noneMatch(t -> Objects.equals(t, e))
                        );
                    }
                    infos = all_infos.collect(Collectors.toList());
                    return JSON.toJSONString(
                            new jResultCrate<>("resp_getInfosByTagUnion", infos)
                    );
                }
                default: {
                    return errInternalError(id + " is not implemented.");
                }
            }
        }

        return JSON.toJSONString(
                new jResultCrate<>("resp_getInfosByTagUnion", infos)
        );
    }
}
